# -*- coding: utf-8 -*-
import json
import os
import random
import re

import time
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.urls import reverse
from xpinyin import Pinyin

import top
# 正则表达式
from newsblog import models
from newsblog.VIP.main import readinfo,savemain
from newsblog.VIP.maokoulingClass import maokouling_ONE, tblink_get_gaoyong, item_to_SELLID, userid_to_shopTBK_link
from newsblog.VIP.player import getPlayList, getPlay
from newsblog.forms import UploadFileForm,Getid
from newsblog.tools.init4words import keywords_list, init_4words
from newsblog.tools.initxiaoshuo import readxiaoshuofromsql
from web.settings import BASE_DIR
from newsblog.VIPsetkeyword.matchKEY import KW_getbackword, KW_getkeyword, KW_readlinks, KW_getwords

# pip install django==2.1.4
# pip install xpinyin
# pip install jsonpath
# pip install django-cors-headers==3.0.2
# python manage.py migrate  #生成数据集

initurl ='tbzhu.com'
# Create your views here.
# 以后使用路径严格按照这个来用：os.path.join(BASE_DIR, 'static\\zhizhulog.txt'   表示从根目录开始
# 远程无法复制粘贴方法：https://jingyan.baidu.com/article/15622f24297b49fdfdbea55f.html
def pinyin(word):
    pin = Pinyin()
    word_pinyin = pin.get_pinyin(word, "")
    return word_pinyin
def index(request):
    #############数据库信息初始化工作###################
    weburl = initurl
    #初始化必备1：xxx网址/upload 上传关键词txt文档，static/keywords/xiaoshuo.txt
    #初始化必备2：static/keywords/xiaoshuo.txt  存入小说txt
    init_4words()
    #############数据库信息初始化结束###################

    # 1-检查Keywords表格中4个扩展信息，并自动生成写入数据库
    xiaoshuotxt = readxiaoshuofromsql()   #从sql中随机取一段文章
    keyworslist = keywords_list()   #推荐列表随机获得4个list,keyworslist[0]是一行数据库数据
    imglist=getimglist()     #推荐列表4张随机图片
    imgpath = 'static\\peoplemod\\img\\'  #推荐列表图片路径设置
    newinfo = zip(keyworslist , imglist)  #推荐列表，zip压缩后赋值
    print("newinfo-------")
    print(keyworslist)

    # List = map(str, range(1000))  # 一个长度为100的 List

    # 判断是否是微信端访问,如果是，返回TRUE，否则返回False
    def if_from_wexin():
        agent = request.META.get('HTTP_USER_AGENT', 'none')
        print(agent)
        print(type(agent))
        wexinuser = re.findall('MicroMessenger',agent)
        if wexinuser:
            return True
        else:
            return False

    #判断是否有对应的关键词，如果有，匹配后返回关键字字符串，否则返回False
    def findkey():
        # 正则匹配二级域名
        # 获取当前访问的域名地址
        keywork = re.compile(r'^([A-Za-z0-9]+)\.'+weburl)

        webpath = request.get_host()  #获取当前访问的网址
        findkey = re.findall(keywork, webpath)
        if findkey:
            return findkey[0]
        else:
            return False

    if findkey():   #如果匹配关键词
        key = findkey()   #关键词为key
        #添加kewordsfix1234匹配
        try:
            keymode = models.KeyWords.objects.get(pinyin=key)
            firstkeywords = keymode.kewordsfix1  # 标题关键词需要固定
            contentkeywords = keymode.kewordsfix1  # 内容关键词需要固定
            key = ''
            return render(request, os.path.join(BASE_DIR, 'templates\\index.html'), locals())  # PC
        except:
            print("数据库无此关键词")

        if if_from_wexin():
            return render(request, os.path.join(BASE_DIR, 'templates\\index.html'), locals())  # PC
        else:
            # return HttpResponse("请在微信客户端内访问")
            # key = "PC访问"
            return render(request, os.path.join(BASE_DIR, 'templates\\index.html'), locals())  # PC
    else:
        key = "省钱好券"
        #禁止使用ip直接访问，禁止本地调试，目前功能禁用
        # return HttpResponseRedirect(f"http://www.{weburl}")
        return render(request, os.path.join(BASE_DIR, 'templates\\index.html'), locals())  # PC
        # return render(request, os.path.join(BASE_DIR, 'templates\\index.html'), locals())  # PC
        # return HttpResponse("你打开错误链接")



def backindex(request):
    key = "主页"
    return render(request, os.path.join(BASE_DIR, 'templates\\index.html'), locals())  # PC



#上传文件处理工具
def handle_upload_file(file):
    with open(os.path.join(BASE_DIR, 'static\\keywords\\keywords.txt'), 'wb+' ) as destination:
        for chunk in file.chunks():
            destination.write(chunk)
    insertmodel()
#读取上传的txt文档并录入数据库，如果失败则删除文件
def insertmodel():
    for line in open(os.path.join(BASE_DIR, 'static\\keywords\\keywords.txt'), errors='ignore'):
        print(type(line))
        try:    # keywords title content author source c_time

            if line.strip() != '':

                try:
                    models.KeyWords.objects.get(keywords=line.strip())
                    print("已存在重复关键词，已去掉" + line.strip())
                except:
                    pinyin1 = pinyin(line.strip())
                    models.KeyWords.objects.create(keywords=line.strip(), pinyin=pinyin1)
                    print('插入成功')
        except:
            print(('没有找到插入失败'))
    if os.path.exists(os.path.join(BASE_DIR, 'static\\keywords\\keywords.txt')):
        os.remove(os.path.join(BASE_DIR, 'static\\keywords\\keywords.txt'))
    return True

def upload(request):
    message = "让我们一起劈荆斩浪！"
    if request.method == 'POST':
        uploadform = UploadFileForm(request.POST,request.FILES)

        if uploadform.is_valid():
            password = uploadform.cleaned_data['password']
            if password == '2019':
                print(password)
                message = "成功上传"
                handle_upload_file(request.FILES.get('file', None))
                ftemp = request.FILES.get('file', None)
                print('ftemp: ', ftemp)
                return render(request, os.path.join(BASE_DIR, 'templates\\upload.html'), locals())
            else:
                message = "协议码错误哦"
                return render(request, os.path.join(BASE_DIR, 'templates\\upload.html'), locals())
        else:
            uploadform = UploadFileForm()
            return render(request, os.path.join(BASE_DIR, 'templates\\upload.html'), locals())
    else:
        uploadform = UploadFileForm()
        print("get请求")
        return render(request, os.path.join(BASE_DIR, 'templates\\upload.html'),locals())

#批量生成图库表,需要的时候写url映射调用生成
def imgupload(request):
    for i in range(100):
        print(i)
        models.Imgfiles.objects.create(img = '%s.jpg' % i)
    return HttpResponse("123")

#随机返回4张图片list
def getimglist():
    n = 4
    i = random.randint(0, models.Imgfiles.objects.count() - n)
    myimgs = list(models.Imgfiles.objects.all()[i:i + n])
    return myimgs


#查出所有数据库表关键词内容，并返回list
def allpinyin_keywords_list(request):
    weburl = initurl
    i =  models.KeyWords.objects.count()
    print(i)
    allkeyword_list = list(models.KeyWords.objects.all())
    print(allkeyword_list)
    # return HttpResponse(allkeyword_list)
    return render(request, os.path.join(BASE_DIR, 'templates\\sitemap.html'), locals())


    # myuser = list(models.KeyWords.objects.all().values())   #获取所有的值
    # print(str(models.KeyWords.objects.all().query))           #打印获取的值
    # print(type(myuser))
    # print('getuserinfo()函数下:', myuser)

def admin123(request):
    zhizhudata = []
    yonghudata = []
    if (os.path.exists(os.path.join(BASE_DIR, 'static\\zhizhulog.txt'))):
            for line in open(os.path.join(BASE_DIR, 'static\\zhizhulog.txt'), "r+", encoding='utf-8', errors='ignore'):  # 设置文件对象并读取每一行文件
                if line.strip() != '':
                    zhizhudata.append(line)
    if (os.path.exists(os.path.join(BASE_DIR, 'static\\yonghu.txt'))):
        for line in open(os.path.join(BASE_DIR, 'static\\yonghu.txt'), "r+", encoding='utf-8', errors='ignore'):  # 设置文件对象并读取每一行文件
            if line.strip() != '':
                yonghudata.append(line)
    return render(request,os.path.join(BASE_DIR, 'templates\\admin123.html'), locals())

def cleartxt(request):
    weburl = initurl
    if (os.path.exists(os.path.join(BASE_DIR, 'static\\yonghu.txt'))):
        os.remove(os.path.join(BASE_DIR, 'static\\yonghu.txt'))
    return HttpResponseRedirect(reverse("admin123"))
def clearzhizhutxt(request):
    weburl = initurl
    if (os.path.exists(os.path.join(BASE_DIR, 'static\\zhizhulog.txt'))):
        os.remove(os.path.join(BASE_DIR, 'static\\zhizhulog.txt'))
    return HttpResponseRedirect(reverse("admin123"))


def getpost(request):
    username = request.GET.get("username")
    print(username)
    try:
        with open(os.path.join(BASE_DIR, f'static\\KEYLOG\\keywordlog.txt'), 'a+', encoding='utf-8', errors='ignore') as f:
            f.write(username+'\n')
        print("sucess")
        print(username)
    except:
        pass
    return HttpResponse("")




def makevip(request):
    weburl = initurl
    KWtitle = f'<p>{KW_getkeyword()}{KW_getbackword()}</p>'
    KWwords = KW_getwords()
    print("1231312")
    xiaoshuotxt = readxiaoshuofromsql()   #从sql中随机取一段文章
    imgpath = 'static\\peoplemod\\img\\'  #推荐列表图片路径设置
    keyworslist = keywords_list()   #推荐列表随机获得4个list,keyworslist[0]是一行数据库数据
    imglist=getimglist()     #推荐列表4张随机图片
    newinfo = zip(keyworslist, imglist)  # 推荐列表，zip压缩后赋值
    return render(request, os.path.join(BASE_DIR, 'templates\\makevip.html'), locals())



# def vip(request):
#     JSONlist = readinfo()
#     print(JSONlist)
#     items = []
#     word =[]
#     pic = []
#     num =0
#     jjword = ''
#     for i in JSONlist:
#         num = num+1
#         # print(i)
#         id = i[0]
#         user_name = i[1]
#         user_face = i[2].replace("http;", "http:")
#         user_date = i[3]
#         user_text = i[4]
#         info = i[5]
#         videoimg = i[6].replace("http;", "http:")
#         videoUrl = i[7].replace("http;", "http:")
#         imglist = i[8].replace("http;", "http:")
#
#         item = {
#             'id': id,
#             'user_name': user_name,
#             'user_face': user_face,
#             'user_date': user_date,
#             'user_text': user_text,
#             'info': info,
#             'videoimg': videoimg,
#             'videoUrl': videoUrl,
#             'imglist': eval(imglist),
#         }
#         items.append(item)
#         if item['imglist'] != 'None':
#             for o in eval(imglist):
#                 # print(o)
#                 pic.append(o)
#
#         jjword = jjword+item['user_text']
#         print(jjword)
#         print(num)
#         if num % 20 == 0:
#             word.append(jjword)
#             jjword = ''
#
#
#     # print(word)
#     # print(pic)
#     abc =zip(word,pic)
#
#     return render(request, os.path.join(BASE_DIR, 'templates\\vip.html'), locals())


# 配置阿里SDK


appkey = '25541421'
secret = ""
url = 'gw.api.taobao.com'
port = 80
#PC端商品展示index数据初始化1
def tbzhushop(request):
    material_id='3786'
    s=init_tbzhu_index(material_id)
    print(type(s))
    # print(s)
    return render(request,os.path.join(BASE_DIR, 'templates\\tbzhushop.html'),{'itemlist':s})

#PC端商品展示index数据初始化2
# 首页商品渠道链接      // 0精选 9660  1女装 9658  2美妆 9653 3鞋包 9648 4美食 9649 5家电 9656 6母婴 9650 7家居 9655 8男装 9654 9运动户外 9651
def init_tbzhu_index(material_id):
    okdict = {'title', 'pict_url', 'item_description','item_id','user_type','coupon_amount','volume','zk_final_price'}
    req = top.api.TbkDgOptimusMaterialRequest(url, port)
    req.set_app_info(top.appinfo(appkey, secret))
    req.page_size = 100
    req.adzone_id = 80892900374
    req.page_no = 1
    req.material_id = material_id
    # req.device_value = "xxx"
    # req.device_encrypt = "MD5"
    # req.device_type = "IMEI"
    # req.content_id = 323
    # req.content_source = "xxx"
    try:
        respdict = req.getResponse()
        print(type(respdict))
        print(respdict)
        listresp = respdict['tbk_dg_optimus_material_response']['result_list']['map_data']
        # print(jsongoods)
        return listresp
    except Exception as e:
        print(e)
        return []

#从前端form表单获取商品的id号码
def tbpinglun(request):
    # material_id='3786'
    # s=init_tbzhu_index(material_id)
    # print(type(s))
    # print(s)
    # {'itemlist': s}
    # itemlist =s
    message = "让我们一起劈荆斩浪！"
    if request.method == 'POST':
        getid = Getid(request.POST)
        if getid.is_valid():
            id = getid.cleaned_data['id']
            message =id
            # 利用VIP目录的maokoulingClass.py 请求商品id获取对应id的URL
            accuntOne = maokouling_ONE()
            accuntOne.itemid =id
            item_TBK_url = tblink_get_gaoyong(accuntOne)
            accuntOne.userid = item_to_SELLID(accuntOne)
            shop_TBK_LINK = userid_to_shopTBK_link(accuntOne)

            #爬取数据开始:
            savemain(id,1)
            time.sleep(0.5)
            savemain(id,2)
            time.sleep(0.5)
            savemain(id,3)
            time.sleep(0.5)
            savemain(id,4)

            #爬取数据结束

            #  读取并整合数据开始，获得某个id的所有db-json数据
            JSONlist = readinfo(id)
            # print(JSONlist)
            items = []  #把db内容读成items列表
            pic = []   #该id下面的数据库存储的图片列表
            picnum =0
            num = 0
            jjword = ''  #累计的一段话，每循环一次，后边组成+一句评价，计数20条后，重新累计成一段话
            word = []  #jjword累计够20条存入word段落中
            wordList = [] #把每行评价都存到list列表里边
            #遍历所有的评论数据
            for i in JSONlist:
                num = num + 1
                id = i[0]  #获取一行db的id数据
                user_name = i[1]  #获取一行db的用户数据
                user_face = i[2].replace("http;", "http:")
                user_date = i[3]
                user_text = i[4]
                info = i[5]
                videoimg = i[6].replace("http;", "http:")
                videoUrl = i[7].replace("http;", "http:")
                imglist = i[8].replace("http;", "http:")

                item = {
                    'id': id,
                    'user_name': user_name,
                    'user_face': user_face,
                    'user_date': user_date,
                    'user_text': user_text,
                    'info': info,
                    'videoimg': videoimg,
                    'videoUrl': videoUrl,
                    'imglist': eval(imglist),  #难点，imglist里边可能有1到n张图片，是个图片列表
                }
                items.append(item)   #items列表内是评价的信息列表
                if item['imglist'] != 'None':   #如果这条评价不为空，就假如pic 列表

                    for o in eval(imglist):
                        if picnum<10:
                            # print(o)
                            pic.append(o)
                        else:break
                picnum = picnum + 1
                jjword = jjword + item['user_text']
                # print(jjword)
                # print(num)
                # print(pic)

                wordList.append(item['user_text'])
                if num == 1 or num ==2 or num ==25 or num ==30 or num ==45 or num ==55 or num ==60:
                    word.append(jjword)
                    jjword = ''
            print('11111111111111111111111111')
            print(len(wordList))
            print(pic)
            dumpspic = json.dumps(pic)
            abc = zip(word, pic)
            ################读取数据并整合结束

            return render(request, os.path.join(BASE_DIR, 'templates\\tbpinglun.html'), locals())

        else:
            pictext =['http://img.alicdn.com/imgextra/i3/0/O1CN01CKTfXF2GKDYEq9FKf_!!0-rate.jpg_400x400.jpg','http://img.alicdn.com/imgextra/i4/0/O1CN018BSh8Z2GKDYFByx6K_!!0-rate.jpg_400x400.jpg']
            dumpspic = json.dumps(pictext)
            getid = Getid()
            return render(request, os.path.join(BASE_DIR, 'templates\\tbpinglun.html'), locals())
    else:
        pictext = ['http://img.alicdn.com/imgextra/i3/0/O1CN01CKTfXF2GKDYEq9FKf_!!0-rate.jpg_400x400.jpg','http://img.alicdn.com/imgextra/i4/0/O1CN018BSh8Z2GKDYFByx6K_!!0-rate.jpg_400x400.jpg']
        dumpspic = json.dumps(pictext)
        getid = Getid()
        print("get请求")
        return render(request, os.path.join(BASE_DIR, 'templates\\tbpinglun.html'),locals())


#富文本编辑器
def editor(request):
    return render(request,os.path.join(BASE_DIR, 'templates\\editor.html'),locals())


def shiyan(request):
    return render(request,os.path.join(BASE_DIR, 'templates\\shiyan.html'),locals())

def vipvideo(request):
    address = request.GET['a']
    print(address)
    list = getPlay(address)
    return render(request,os.path.join(BASE_DIR, 'templates\\vipvideo.html'),locals())

def playlist(request):
    try:
        password = request.GET['a']
        # print(password)
        if password =='2019666':
            list =getPlayList()
            # print(list)
        return render(request,os.path.join(BASE_DIR, 'templates\\playlist.html'),locals())
    except:
        return render(request,os.path.join(BASE_DIR, 'templates\\playlist.html'),locals())



def ewm(request):
    return render(request, os.path.join(BASE_DIR, 'templates\\ewm.html'), locals())

def initedit(request):
    return render(request, os.path.join(BASE_DIR, 'templates\\initedit.html'), locals())

def vip(request):
    return render(request, os.path.join(BASE_DIR, 'templates\\vip.html'), locals())

def codefenxi1(request):
    return render(request, os.path.join(BASE_DIR, 'templates\\fenxi\\codefenxi1.html'), locals())

def codefenxi2(request):
    return render(request, os.path.join(BASE_DIR, 'templates\\fenxi\\codefenxi2.html'), locals())





